package main

import (
	"ifms/db_svr"
	"ifms/tde_servicer"
	"log"
	"net"
	_ "net/http/pprof"
	"os"
)

var logger *log.Logger = log.New(os.Stdout, "Tde_Main ", log.LstdFlags|log.Lshortfile)

// will be initilized by build parameter
// -ldflags="-X main.version=$(git describe --always --long --dirty)"

// var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

var version string

func main() {

	// flag.Parse()
	// if *cpuprofile != "" {
	// 	f, err := os.Create(*cpuprofile)
	// 	if err != nil {
	// 		log.Fatal(err)
	// 	}
	// 	pprof.StartCPUProfile(f)
	// 	logger.Printf("CPU profile at : %v ..... \n", cpuprofile)
	// 	defer pprof.StopCPUProfile()
	// }

	// go func() {
	// 	pprofport := os.Getenv("PPROFPORT")
	// 	if len(pprofport) < 2 {
	// 		pprofport = ":6061"
	// 	}
	// 	logger.Println("pprof TDE server staring.... ", http.ListenAndServe("localhost"+pprofport, http.DefaultServeMux), "  started")
	// }()

	//before connected to the DB , do not start accept the client TCP connection
	<-db_svr.DB_Connected

	port := os.Getenv("EPRT") //":9715"

	/*
		server := tde_servicer.CreateTcpServer()

		logger.Printf("TDE Servicer started, running on %s. \n", port)
		logger.Printf("Version: %v \n", version)

		server.Start(port)
	*/

	l, err := net.Listen("tcp", port)
	checkError(err)
	defer l.Close()
	logger.Printf("TDE Servicer started, running on %s. \n", port)
	logger.Printf("Version: %v \n", version)
	for {
		// Wait for a connection.
		conn, err := l.Accept()
		checkError(err)
		// Handle the connection in a new goroutine.
		// The loop then returns to accepting, so that
		// multiple connections may be served concurrently.
		go tde_servicer.Tde_session(conn)

	}

}

func checkError(err error) {
	if err != nil {
		logger.Printf("Fatal error: %s\n", err.Error())
		os.Exit(1)
	}
}
